package com.example.demo.service;

import com.example.demo.entity.Book;
import com.example.demo.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class BookService {

    @Autowired
    private BookMapper bookMapper;

    public List<Book> findAll() {
        return bookMapper.findAll();
    }

    public Book findById(Long id) {
        return bookMapper.findById(id);
    }

    public int save(Book book) {
        if (book.getId() == null) {
            // Check if a book with the same ISBN already exists
            if (book.getIsbn() != null && findByIsbn(book.getIsbn()) != null) {
                return -1; // Indicate that the book already exists
            }
            return bookMapper.insert(book);
        } else {
            return bookMapper.update(book);
        }
    }

    public int deleteById(Long id) {
        return bookMapper.deleteById(id);
    }

    public List<Book> findByTitleContaining(String title) {
        return bookMapper.findByTitleContaining(title);
    }

    public Book findByIsbn(String isbn) {
        return bookMapper.findByIsbn(isbn);
    }

    public List<Book> searchBooks(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return bookMapper.findAll();
        }
        // Assuming you have a method in BookMapper to search by title, author, or ISBN
        // You might need to implement this in BookMapper.java and BookMapper.xml
        return bookMapper.searchBooks(keyword);
    }
}